// 全局变量
let matchesData = [];
let uniquePlayers = new Set();

// DOM 元素
const csvFileInput = document.getElementById('csvFile');
const importBtn = document.getElementById('importBtn');
const leftPlayerSelect = document.getElementById('leftPlayer');
const rightPlayerSelect = document.getElementById('rightPlayer');
const filterBtn = document.getElementById('filterBtn');
const analyzeBtn = document.getElementById('analyzeBtn');
const matchesTable = document.getElementById('matchesTable');
const analysisResult = document.getElementById('analysisResult');

// 从URL加载CSV
const loadFromURLBtn = document.getElementById('loadFromURLBtn');

// Function to load CSV from URL
async function loadCSVFromURL(url) {
    try {
        const response = await fetch(url);
        const csvContent = await response.text();
        processCSVData(csvContent);
    } catch (error) {
        console.error('Error loading CSV from URL:', error);
        alert(`Failed to load CSV from URL: ${url}`);
    }
}

// Get base URL
function getBaseURL(url) {
    try {
        const urlObject = new URL(url);
        let baseUrl = urlObject.origin;
        // Split the pathname into segments and remove the last segment
        const pathSegments = urlObject.pathname.split('/').filter(segment => segment !== ''); // Split and remove empty strings
        if (pathSegments.length > 1) {
            pathSegments.pop(); // Remove the last segment
            baseUrl = urlObject.origin + '/' + pathSegments.join('/'); // Reconstruct the path
        }
        return baseUrl;
    } catch (error) {
        console.error("Invalid URL:", url, error);
        return null; // Or handle the error as appropriate
    }
}

// 导入CSV文件
function importCSV() {
    const file = csvFileInput.files[0];
    if (!file) {
        alert('请选择一个CSV文件');
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        const content = e.target.result;
        processCSVData(content);
    };
    reader.readAsText(file);
}

// 处理CSV数据
function processCSVData(csvContent) {
    // 重置数据
    matchesData = [];
    uniquePlayers.clear();
    
    // 解析CSV
    const lines = csvContent.split('\n');
    
    // 跳过标题行，从第二行开始处理
    for (let i = 1; i < lines.length; i++) {
        if (!lines[i].trim()) continue; // 跳过空行
        
        const columns = parseCSVLine(lines[i]);
        
        if (columns.length >= 10) {
            const match = {
                round: columns[0],
                time: columns[1],
                leftPlayer: columns[2],
                leftOdds: parseFloat(columns[3]) || 0,
                rightPlayer: columns[4],
                rightOdds: parseFloat(columns[5]) || 0,
                disadvantage1: columns[6],
                disadvantage2: columns[7],
                disadvantage3: columns[8],
                winner: columns[9]
            };
            
            matchesData.push(match);
            
            // 收集唯一选手名称
            if (match.leftPlayer) uniquePlayers.add(match.leftPlayer);
            if (match.rightPlayer) uniquePlayers.add(match.rightPlayer);
        }
    }
    
    // 更新选手下拉列表
    updatePlayerDropdowns();
    
    // 显示所有数据
    displayMatches(matchesData);
}

// 解析CSV行，处理引号内的逗号
function parseCSVLine(line) {
    const result = [];
    let current = '';
    let inQuotes = false;
    
    for (let i = 0; i < line.length; i++) {
        const char = line[i];
        
        if (char === '"' && (i === 0 || line[i-1] !== '\\')) {
            inQuotes = !inQuotes;
        } else if (char === ',' && !inQuotes) {
            result.push(current);
            current = '';
        } else {
            current += char;
        }
    }
    
    result.push(current); // 添加最后一列
    return result;
}

// 更新选手下拉列表
function updatePlayerDropdowns() {
    // 清空现有选项
    leftPlayerSelect.innerHTML = '<option value="">选择选手</option>';
    rightPlayerSelect.innerHTML = '<option value="">选择选手</option>';
    
    // 添加所有选手
    const sortedPlayers = Array.from(uniquePlayers).sort();
    sortedPlayers.forEach(player => {
        const leftOption = document.createElement('option');
        leftOption.value = player;
        leftOption.textContent = player;
        leftPlayerSelect.appendChild(leftOption);
        
        const rightOption = document.createElement('option');
        rightOption.value = player;
        rightOption.textContent = player;
        rightPlayerSelect.appendChild(rightOption);
    });
}


// 高亮赔率
function displayOdds(odds) {
    let cell = '';
    if (odds >= 4) {
        cell = '<span class="high-score">' + odds + '</span>';
    } else if (odds >= 3.5) {
        cell = '<span class="middle-score">' + odds + '</span>';
    } else {
        cell = odds
    }
    return cell
}

// 显示比赛数据
function displayMatches(matches) {
    const tbody = matchesTable.querySelector('tbody');
    tbody.innerHTML = '';
    
    matches.forEach(match => {
        const row = document.createElement('tr');
        
        let leftPlayerCell = '';
        let rightPlayerCell = '';
        
        if (match.winner === match.leftPlayer) {
            leftPlayerCell = '<span class="highlighted">' + match.leftPlayer + '</span>';
            rightPlayerCell = match.rightPlayer;
        } else if (match.winner === match.rightPlayer) {
            rightPlayerCell = '<span class="highlighted">' + match.rightPlayer + '</span>';
            leftPlayerCell = match.leftPlayer;
        } else {
            leftPlayerCell = match.leftPlayer;
            rightPlayerCell = match.rightPlayer;
        }
        
        row.innerHTML = `
            <td>${match.round}</td>
            <td>${match.time}</td>
            <td>${leftPlayerCell}</td>
            <td>${displayOdds(match.leftOdds)}</td>
            <td>${rightPlayerCell}</td>
            <td>${displayOdds(match.rightOdds)}</td>
            <td>${match.disadvantage1}↓</td>
            <td>${match.disadvantage2}↓</td>
            <td>${match.disadvantage3}↓</td>
            <td>${match.winner}</td>
        `;
        
        tbody.appendChild(row);
    });
}

// 筛选比赛
function filterMatches() {
    const leftPlayer = leftPlayerSelect.value;
    const rightPlayer = rightPlayerSelect.value;
    
    if (!leftPlayer || !rightPlayer) {
        alert('请选择两位选手');
        return;
    }
    
    // 筛选出包含两位选手的比赛（左右可互换）
    const filteredMatches = matchesData.filter(match => {
        return (
            (match.leftPlayer === leftPlayer && match.rightPlayer === rightPlayer) ||
            (match.leftPlayer === rightPlayer && match.rightPlayer === leftPlayer)
        );
    });
    
    // 显示筛选结果
    displayMatches(filteredMatches);
    
    // 高亮显示筛选的行
    // const rows = matchesTable.querySelectorAll('tbody tr');
    // rows.forEach(row => {
    //     row.classList.add('highlighted');
    // });
    
    // 隐藏分析结果
    analysisResult.classList.remove('show');
}

// 分析比赛
function analyzeMatches() {
    const leftPlayer = leftPlayerSelect.value;
    const rightPlayer = rightPlayerSelect.value;
    
    if (!leftPlayer || !rightPlayer) {
        alert('请选择两位选手');
        return;
    }
    
    // 筛选出包含两位选手的比赛（左右可互换）
    const filteredMatches = matchesData.filter(match => {
        return (
            (match.leftPlayer === leftPlayer && match.rightPlayer === rightPlayer) ||
            (match.leftPlayer === rightPlayer && match.rightPlayer === leftPlayer)
        );
    });
    
    if (filteredMatches.length === 0) {
        analysisResult.innerHTML = '没有找到这两位选手的比赛记录';
        analysisResult.classList.add('show');
        return;
    }
    
    // 计算胜率
    let leftPlayerWins = 0;
    let rightPlayerWins = 0;
    
    filteredMatches.forEach(match => {
        if (match.winner === leftPlayer) {
            leftPlayerWins++;
        } else if (match.winner === rightPlayer) {
            rightPlayerWins++;
        }
    });
    
    const totalMatches = filteredMatches.length;
    const leftWinRate = (leftPlayerWins / totalMatches * 100).toFixed(2);
    const rightWinRate = (rightPlayerWins / totalMatches * 100).toFixed(2);
    
    // 显示分析结果
    analysisResult.innerHTML = `
        <h3>历史对战分析</h3>
        <p>总比赛场数: ${totalMatches}</p>
        <p>${leftPlayer} 胜场: ${leftPlayerWins} (胜率: ${leftWinRate}%)</p>
        <p>${rightPlayer} 胜场: ${rightPlayerWins} (胜率: ${rightWinRate}%)</p>
    `;
    analysisResult.classList.add('show');
    
    // 显示筛选结果
    displayMatches(filteredMatches);
    
    // 高亮显示筛选的行
    // const rows = matchesTable.querySelectorAll('tbody tr');
    // rows.forEach(row => {
    //     row.classList.add('highlighted');
    // });
}

// 创建示例CSV数据用于测试
function createSampleCSV() {
    return `场次,时间,左侧选手,左侧赔率,右侧选手,右侧赔率,减益1,减益2,减益3,胜者
1,2025-03-12 16:00,杰伦塔尼娅,2.8,蕾米娅,2.1,0.68,0,0.32,蕾米娅 
2,2025-03-12 20:00,蕾米娅,2,书包酱,3,0.68,0,0.32,书包酱
3,2025-03-13 00:00,书包酱,3.8,苏尔,1.7,0.68,0,0.32,书包酱
4,2025-03-13 12:00,苏尔,1.8,杰伦塔尼娅,3.4,0.68,0,0.32,杰伦塔尼娅
5,2025-03-13 20:00,杰伦塔尼娅,2.2,书包酱,2.6,0.68,0,0.32,杰伦塔尼娅
6,2025-03-14 00:00,蕾米娅,2.9,苏尔,2,0.68,0,0.32,蕾米娅
7,2025-03-14 12:00,书包酱,2.6,杰伦塔尼娅,2.2,0.68,0,0.32,杰伦塔尼娅
8,2025-03-14 20:00,苏尔,2,蕾米娅,2.9,0.68,0,0.32,苏尔
9,2025-03-15 00:00,杰伦塔尼娅,3.4,苏尔,1.8,0.68,0,0.32,杰伦塔尼娅
10,2025-03-15 12:00,蕾米娅,2.1,杰伦塔尼娅,2.8,0.68,0,0.32,杰伦塔尼娅
11,2025-03-15 20:00,书包酱,3,蕾米娅,2,0.68,0,0.32,蕾米娅
12,2025-03-16 00:00,苏尔,1.7,书包酱,3.8,0.68,0,0.32,苏尔
13,2025-03-16 12:00,杰伦塔尼娅,2.2,蕾米娅,2.5,0.65,0.35,0,杰伦塔尼娅
14,2025-03-16 20:00,蕾米娅,1.8,书包酱,3.6,0.65,0.35,0,蕾米娅
15,2025-03-17 00:00,书包酱,3.7,苏尔,1.7,0.65,0.35,0,苏尔
16,2025-03-17 12:00,苏尔,2.5,杰伦塔尼娅,2.3,0.65,0.35,0,杰伦塔尼娅
17,2025-03-17 20:00,杰伦塔尼娅,1.7,书包酱,3.9,0.65,0.35,0,书包酱
18,2025-03-18 00:00,蕾米娅,2.4,苏尔,2.3,0.65,0.35,0,蕾米娅
19,2025-03-18 12:00,书包酱,3.9,杰伦塔尼娅,1.7,0.65,0.35,0,书包酱
20,2025-03-18 20:00,苏尔,2.3,蕾米娅,2.4,0.65,0.35,0,蕾米娅`;
}

// 添加下载示例CSV的功能
function downloadSampleCSV() {
    const csvContent = createSampleCSV();
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', '示例数据.csv');
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 页面加载完成后初始化事件监听器
document.addEventListener('DOMContentLoaded', () => {
    // 添加事件监听器
    importBtn.addEventListener('click', importCSV);
    filterBtn.addEventListener('click', filterMatches);
    analyzeBtn.addEventListener('click', analyzeMatches);
    
    // 添加示例数据按钮事件
    const sampleBtn = document.getElementById('sampleBtn');
    sampleBtn.addEventListener('click', () => {
        // processCSVData(createSampleCSV());
        loadCSVFromURL(getBaseURL(location.href) + '/bh2.csv')
    });
    
    // 添加下载示例CSV按钮事件
    const downloadSampleBtn = document.getElementById('downloadSampleBtn');
    downloadSampleBtn.addEventListener('click', downloadSampleCSV);
    
    // 添加从URL加载按钮事件
    loadFromURLBtn.addEventListener('click', () => {
        const url = prompt('请输入CSV文件的URL:');
        if (url) {
            loadCSVFromURL(url);
        }
    });
});

loadCSVFromURL(getBaseURL(location.href) + '/bh2.csv');
